var entityCollection = require('../../../Base/server/controllers/EntityCollection');

exports.updateApps = function(apps, resultHandel){
	var entity = entityCollection.getEntity("App");
	var datas = [];
	if(apps.length > 0){
		for (var i = 0, len = apps.length; i < len; i++) {
			datas.push({ 
				updateOne: {
					filter: { AppID: apps[i].AppID },
					update: { $set: apps[i] },
					upsert: true
				}
			});
		}

		entity.Entity.collection.bulkWrite(datas, {ordered: false}, function(err, data){
			if(err){
				resultHandel(err);
			}
			else{
				resultHandel(null, data);
			}
		});
	}
	else{
		resultHandel(null, true);
	}
};

//根据用户记录获取角色信息集合
exports.getApps = function(userId, type, resultHandel){
	var entity = entityCollection.getEntity("User");
	entity.findOne({_id: userId}, {
			path: 'AppRoles', 
			select: 'Apps', 
			populate: {
				path: 'Apps',
				select: 'AppID Name FileName DisplayImage MouseDownImage Version Type',
				model: 'App'
			}
		}, function(err, record){
			if(err || !record){
				resultHandel(err);
			}
			else{
				var apps = [];
				for(var i=0; i<record.AppRoles.length; i++){
					for(var j=0; j<record.AppRoles[i].Apps.length; j++){
						if (record.AppRoles[i].Apps[j].Type !== type) {
							continue;
						}
						//检查是否有重复，因为不同角色里面可能存在重复的App
						var isFind = false;
						for(var n=0; n<apps.length; n++){
							if(apps[n].AppID == record.AppRoles[i].Apps[j].AppID){
								isFind = true;
								break;
							}
						}
						if(!isFind){
							apps.push(record.AppRoles[i].Apps[j]);
						}
					}
				}		
				resultHandel(null, apps);
			}
		}
	);
};

exports.getAppByAppId = function(appId, resultHandel){
	var entity = entityCollection.getEntity("App");
	entity.findOne({AppID: appId}, null, function(err, record){
		if(err){
			resultHandel(err);
		}
		else{
			resultHandel(null, record);
		}
	});
};